package zhtt.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import zhtt.example.entry.ServiceInstanceInfo;

import java.util.List;

@Service
public class DiscoveryService {

    private final DiscoveryClient discoveryClient;

    @Autowired
    public DiscoveryService(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    public Flux<String> getServiceNames() {
        // 获取所有服务名称
        List<String> services = discoveryClient.getServices();
        return Flux.fromIterable(services);
    }

    public Flux<ServiceInstanceInfo> getServiceInstances(String serviceName) {
        // 获取指定服务的所有实例
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        return Flux.fromIterable(instances)
                .map(instance -> new ServiceInstanceInfo(
                        instance.getServiceId(),
                        instance.getHost(),
                        instance.getPort()
                ));
    }
}
